package com.yufei.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yufei.dto.DishDto;
import com.yufei.common.R;
import com.yufei.entity.Category;
import com.yufei.entity.Dish;
import com.yufei.entity.DishFlavor;
import com.yufei.entity.SetmealDish;
import com.yufei.mapper.DishMapper;
import com.yufei.service.CategoryService;
import com.yufei.service.DishFlavorService;
import com.yufei.service.DishService;
import com.yufei.service.SetmealDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 分页显示全部菜品
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/dish/page")
    public R<Page<DishDto>> getDishPage(Integer page, Integer pageSize,Dish dish) {
        // 创建分页对象及查询条件
        Page<Dish> dishPage = new Page<>(page, pageSize);
        QueryWrapper<Dish> wrapper1 = new QueryWrapper<>();

        //判断是否有模糊查询,有菜名就是模糊查询
        String name = dish.getName();
        wrapper1.like(StringUtils.hasText(name),"name", name);

        wrapper1.orderByAsc("sort");  // 按照sort字段升序排序
        wrapper1.eq("is_deleted", 0);//判断是否被删除
        // 查询菜品信息并进行分页
        dishPage = dishService.page(dishPage, wrapper1);

        // 创建一个新的分页对象来存放Dto类型的数据
        Page<DishDto> dishDtoPage = new Page<>();
        //将dishpage复制到dishDtoPage，不赋值records
        BeanUtils.copyProperties(dishPage, dishDtoPage,"records");
        List<Dish> records = dishPage.getRecords();
        //处理获取
        List<DishDto> collect = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将dish放到dishDto中CategoryName
            BeanUtils.copyProperties(item, dishDto);
            Category category = categoryService.getById(dishDto.getCategoryId());
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(collect);

        return R.success(dishDtoPage);
    }

    /**
     * 删除接口
     * @param ids 使用string接收为了实现批量删除
     * @return
     */
    @DeleteMapping("/dish")
    public R<String> deleteDish(String ids) {
        // 处理 ids 参数，转换为一个列表
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        for (Long id : idList) {
            /**
             * 当删除菜品时，需要判断是否存在套餐包含该菜品，有则不能删除
             */
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("dish_id", id);
            queryWrapper.eq("is_deleted", 0);
            List list = setmealDishService.list(queryWrapper);
            if(list != null && list.size() > 0) {
                return R.error("删除失败，存在套餐包含该菜品");
            }
            //开始执行删除操作
            UpdateWrapper<Dish> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", id);
            wrapper.set("is_deleted", 1);
            //更新is_deleted为1，标识删除
            dishService.update(wrapper);
        }
        return R.success("删除成功！");
    }
    /**
     * 修改商品信息回显功能
     * 已成功
     */
    @GetMapping("/dish/{id}")
    public R<DishDto> queryDishById(@PathVariable("id") Integer id) {
        Dish dish = dishService.getById(id);
        DishDto dto = new DishDto();
        /**
         * 先获取dish的信息
         */
        BeanUtils.copyProperties(dish, dto);
        /**
         * 查询种类名并放入dto中
         */
        dto.setCategoryName(categoryService.getById(dish.getCategoryId()).getName());
        /**
         * 查询口味信息并放到dto中
         */
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id",dish.getId());
        queryWrapper.eq("is_deleted",0);
        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);
        dto.setFlavors(dishFlavors);
        //返回
        return R.success(dto);
    }

    /**
     * 修改菜品接口
     * 增加保存菜品口味信息
     */
    @PutMapping("/dish")
    public R<String> editDish(HttpServletRequest request, @RequestBody DishDto dto) {
        Long employee1 = (Long) request.getSession().getAttribute("employee");
        dto.setUpdateTime(new Date());
        dto.setUpdateUser(employee1);
        //Dish表可以直接更新
        dishService.updateById(dto);

        //更新dish_flavor表，先把原来的删除,把is_deletded置为1
        UpdateWrapper<DishFlavor> wrapper = new UpdateWrapper<>();
        wrapper.eq("dish_id", dto.getId());
        wrapper.set("is_deleted", 1);
        dishFlavorService.update(wrapper);
        //再新增加
        Long dishId = dto.getId();
        List<DishFlavor> dishFlavors = dto.getFlavors();
        for (DishFlavor df : dishFlavors) {
            //清空原有id
            df.setId(null);

            df.setDishId(dishId);
            df.setCreateTime(new Date());
            df.setUpdateTime(new Date());
            df.setCreateUser(employee1);
            df.setUpdateUser(employee1);
        }
        //批量保存
        dishFlavorService.saveBatch(dishFlavors);
        return R.success("修改成功");
    }

    /**
     * 新增菜品接口
     * 需要把口味信息存到口味表中
     */
    @PostMapping("/dish")
    public R<String> addDish(HttpServletRequest request , @RequestBody DishDto dto) {
        Long employee1 = (Long) request.getSession().getAttribute("employee");
        dto.setCreateTime(new Date());
        dto.setUpdateTime(new Date());
        dto.setCreateUser(employee1);
        dto.setUpdateUser(employee1);
        boolean isok = dishService.save(dto);
        Long dishId = dto.getId();
        List<DishFlavor> dishFlavors = dto.getFlavors();
        for (DishFlavor df : dishFlavors) {
            df.setDishId(dishId);
            df.setCreateTime(new Date());
            df.setUpdateTime(new Date());
            df.setCreateUser(employee1);
            df.setUpdateUser(employee1);
        }
        //批量保存
        boolean isok1 = dishFlavorService.saveBatch(dishFlavors);
        if(isok && isok1){
            return R.success("添加成功！");
        }else {
            return R.error("添加失败!");
        }
    }
    /**
     *  起售停售---批量起售停售接口
     */
    @PostMapping("/dish/status/{params.status}")
    public R<String> dishStatusByStatus(HttpServletRequest request,
                                        @PathVariable("params.status") Integer status,String ids) {
        Long employee1 = (Long) request.getSession().getAttribute("employee");
        // 打印接收到的参数
        System.out.println("Status: " + status);
        System.out.println("IDs: " + ids);
        // 处理 ids 参数，转换为一个列表
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        for (Long id : idList) {
            Dish dish = dishService.getById(id);
            //更新状态
            dish.setStatus(status);
            //设置更新时间
            dish.setUpdateTime(new Date());
            //设置更新人员
            dish.setUpdateUser(employee1);
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", dish.getId());
            dishService.update(dish, queryWrapper);
        }
        return R.success("更新成功！");
    }
    /**
     *新增套餐时，获取菜品列表
     */
    @GetMapping("/dish/list")
    public R<List<DishDto>> listCategory(Dish dish) {
        //创建查询对象
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();

        //判断是否为模糊查询
        String name = dish.getName();
        wrapper.like(StringUtils.hasText(name),"name", name);

        //查询的为该种类对应的全部菜品
        //CategoryId不为空才加上这个查询条件，此时为模糊查询
        if(dish.getCategoryId() != null) {
            wrapper.eq("category_id", dish.getCategoryId());
        }

        //只查询在销售的,即为1的
        wrapper.eq("status", 1);
        //排序
        wrapper.orderByAsc("sort","update_time");
        //查询dish
        List<Dish> dishList = dishService.list(wrapper);
        /**
         * 继续查询
         */
        List<DishDto> dishDtoList = new ArrayList<>();
        dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();

            //根据id查询分类对象，赋值categoryName
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //根据当前菜品的id查询菜品表下对应的口味
            Long dishId = item.getId();
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dish_id", dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;

        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }
}
